import { Injectable, Logger } from '@nestjs/common';
import { CreateResultDto } from './dto/create-result.dto';
import { Result } from './entities/result.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

function randomNum() {
  return Math.floor(Math.random() * 1000000);
}

@Injectable()
export class ResultService {
  private logger = new Logger();
  @InjectRepository(Result)
  private resultRepository: Repository<Result>;
  // 创建一个create方法，接收一个CreateResultDto类型的参数
  // 该方法返回一个Promise<Result>类型的对象
  async create(createResultDto: CreateResultDto) {
    // 创建一个Result对象
    const result = new Result();
    result.id = randomNum();
    result.userId = createResultDto.userId;
    result.userName = createResultDto.userName;
    result.time = createResultDto.time;
    result.errorNum = createResultDto.errorNum;
    result.createTime = new Date();
    try {
      await this.resultRepository.save(result);
      return '创建成功';
    } catch (error) {
      this.logger.error(error, ResultService);
      return '创建失败';
    }
  }
  // 创建一个list方法，返回一个Promise<Result[]>类型的对象
  async list() {
    const [list, totalCount] = await this.resultRepository.findAndCount({});
    return {
      list,
      totalCount,
    };
  }

  async findByUserId(userId: number) {
    const [list, totalCount] = await this.resultRepository.findAndCount({
      where: {
        userId,
      },
    });
    return {
      list,
      totalCount,
    };
  }
}
